import { Creature, Feature, Glyph } from '$lib/components';
import { Ground } from '$lib/content/ground';
import { Item } from '$lib/item';
import { decode } from '$lib/util';
import { hasComponent } from '$lib/ecs';
import { Coal, Foliage, Gold } from './ground';
import { Surface } from './ship';

export const renderStack = (world, stack) => {
  let entity;
  let etype: string;
  let background = '#888';
  for (let e of stack) {
    if (hasComponent(world, Creature, e)) {
      entity = e;
      etype = 'creature';
    } else if (hasComponent(world, Item, e) && etype !== 'creature') {
      entity = e;
      etype = 'item';
    } else if (hasComponent(world, Feature, e) && etype !== 'item' && etype !== 'creature') {
      entity = e;
      etype = 'feature';
    } else if (hasComponent(world, Ground, e)) {
      if (etype === undefined) {
        entity = e;
        etype = 'ground';
      }
      const ebg = decode(Glyph.background[e]);
      if (ebg) {
        background = ebg;
      }
      if (hasComponent(world, Foliage, e)) {
        const amount = Foliage.amount[e];
        // TODO: gradient!
        background = `color-mix(in lch, ${background}, #4a6 ${amount/100*100}%)`;
      }
      if (hasComponent(world, Coal, e)) {
        const amount = Coal.amount[e];
        background = `color-mix(in lch, ${background}, #000 ${amount/100*100}%)`;
      }
      if (hasComponent(world, Gold, e)) {
        const amount = Gold.amount[e];
        background = `color-mix(in lch, ${background}, #b50 ${amount/100*100}%)`;
      }
    }
    if (hasComponent(world, Surface, e)) {
      background = decode(Glyph.background[e]);
    }
  }
  if (entity === undefined) {
    return { glyph: ' ' };
  }
  const glyph = decode(Glyph.glyph[entity]);
  const color = decode(Glyph.color[entity]);
  return {
    glyph,
    color,
    background,
  };
};
